package com.bird.generate.ddd.domain

import cn.hutool.core.io.FileUtil
import cn.hutool.core.util.ZipUtil
import com.bird.component.lang.common.exception.ServiceException
import com.bird.generate.ddd.domain.generateutil.AdapterGenerate
import com.bird.generate.ddd.domain.generateutil.ClientGenerate
import com.bird.generate.ddd.domain.generateutil.DomainGenerate
import com.bird.generate.ddd.domain.generateutil.LocalGenerate
import com.bird.generate.ddd.domain.generateutil.ModuleGenerate
import com.bird.generate.ddd.domain.generateutil.RemoteGenerate
import com.bird.generate.ddd.domain.port.GenerateRepository
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStreamWriter
import java.nio.charset.Charset

/**
 * 生成处理器
 */
class GenerateHandler(private val generateRepository: GenerateRepository) {

    fun generate(path: String,id: Long) {
        val aggregateRootEntity = generateRepository.aggregateRootById(id) ?: throw ServiceException("聚合根不存在")
        DomainGenerate.domainGenerate(path,aggregateRootEntity)
        AdapterGenerate.adapterGenerate(path,aggregateRootEntity)
        ClientGenerate.clientGenerate(path,aggregateRootEntity)
        LocalGenerate.adapterGenerate(path,aggregateRootEntity)
        RemoteGenerate.adapterGenerate(path,aggregateRootEntity)
        ModuleGenerate.moduleGenerate(path,aggregateRootEntity)
    }

    /**
     * 添加聚合根
     */
    fun addAggregateRoot(aggregateRoot: AggregateRootEntity):Long? {
        aggregateRoot.toNew()
        aggregateRoot.entities.forEach {
            it.toNew()
        }
        aggregateRoot.emptyFieldsDeal()
        aggregateRoot.oneFieldValueObjectDeal()
        aggregateRoot.valueObjects.forEach {
            it.toNew()
        }
        generateRepository.saveAggregateRoot(aggregateRoot)
        return aggregateRoot.id
    }

    fun download(path: String, name: kotlin.String): File {
        var file = FileUtil.file(path)
        //file文件夹下的所有文件，生成zip
        val zip = ZipUtil.zip(file)
        FileUtil.del(file)
        return zip
    }

}




fun String.appendNextPath(nextPath: String): String {
    //如果当前地址的最后一个字符是/，去掉它
    //如果nextPath的第一个字符是/，去掉它
    return if (this.endsWith("/")) {
        if (nextPath.startsWith("/")) {
            this + nextPath.substring(1)
        } else {
            this + nextPath
        }
    } else {
        if (nextPath.startsWith("/")) {
            this + nextPath
        } else {
            "$this/$nextPath"
        }
    }
}

fun createFile(fullPathname:String,content:String){
    var path = fullPathname.substringBeforeLast("/")
    val file = File(path)
    if (!file.exists()) {
        FileUtil.mkdir(file)
    }
    if (content.isNotBlank()) {
        val fileOutputStream = FileOutputStream(fullPathname, false)
        val outputStreamWriter = OutputStreamWriter(fileOutputStream, Charset.defaultCharset())
        outputStreamWriter.write(content)
        outputStreamWriter.write("\n")
        outputStreamWriter.close()
        fileOutputStream.close()
    }

}
/**
 * 生成包信息
 */
fun generatePackageInfo(path: String,javaPath:String) {
    val content = """
package ${javaPath.replace("/", ".")};
        """
    createFile(path.appendNextPath("package-info.java"), content)
}

val JAVA_PATH = "/src/main/java"